package com.loiot.baqi.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiot.baqi.constant.Const;
import com.loiot.baqi.constant.URLConst;
import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.pojo.TgAccount;
import com.loiot.baqi.pojo.TgQqGroup;
import com.loiot.baqi.pojo.WeiAccountQqGroup;
import com.loiot.baqi.service.TgAccountService;
import com.loiot.baqi.service.TgQqGroupService;
import com.loiot.baqi.service.WeiAccountQqGroupService;
import com.loiot.baqi.status.AssignmentStatus;
import com.loiot.baqi.status.ImportStatus;
import com.loiot.baqi.status.JoinStatus;
import com.loiot.baqi.status.KickStatus;
import com.loiot.baqi.status.PauseStartType;
import com.loiot.baqi.status.PlatAccountType;
import com.loiot.commons.message.util.JsonUtil;
import com.timeloit.pojo.Account;

/**
 * “用户_QQ群” 处理器。 WeiAccountQqGroup
 * 
 * @author wangzx
 * @creation 2016-03-21
 */

@Controller
@RequestMapping(value = "/weiAccountQqGroup")
public class WeiAccountQqGroupController {

	public static final AjaxResponse GROUP_ASSIGNED = new AjaxResponse(-100,
			"群已分配");

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource
	private WeiAccountQqGroupService weiAccountQqGroupService;

    @Resource
    private TgAccountService tgAccountService;
    
    
	private WeiAccountQqGroup weiAccountQqGroup;

	private HashMap<String, Object> pmap = new HashMap<String, Object>();
	
	 @Resource
     private TgQqGroupService tgQqGroupService;

	/**
	 * 跳转 “用户_QQ群”概览列表页
	 * 
	 * @return 模板位置
	 */
	@RequestMapping(value = "/overviewList")
	public String overviewList(
			@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
			WeiAccountQqGroup p, ModelMap model) throws Exception {
		HashMap<String, Object> paramMap = this.getParaMap(jsonParam, model);
		paramMap.put("qtype", "like");
		Pager<WeiAccountQqGroup> pager = weiAccountQqGroupService
				.queryWeiAccountQqGroupOverviewListPage(paramMap, pageIndex);
		model.put("pager", pager);
		model.put("jsonParam", jsonParam);
		return "/weiAccountQqGroup/weiAccountQqGroupOverview_list";
	}

	/**
	 * 跳转 用户_QQ群列表页
	 * 
	 * @return 模板位置
	 */
	@RequestMapping(value = "/list")
	public String list(
			@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
			WeiAccountQqGroup p, ModelMap model) throws Exception {
        HashMap<String, Object> paramMap = this.getParaMap(jsonParam, model);
        if(p.getAccountId() != null){
        	paramMap.put("accountId", p.getAccountId());
        	TgAccount account = tgAccountService.getTgAccountById(p.getAccountId());
        	model.put("realName", account.getRealName());
        }
		paramMap.put("qtype", "like");
		// 用户数据过滤
		/*
		 * if(UserSessionUtils.getAccountType()==AccountType.HR.getCode() ||
		 * UserSessionUtils.getAccountType()==AccountType.JOB_HUNTER.getCode()
		 * ){ paramMap.put("inPerson",
		 * UserSessionUtils.getAccount().getAccountId()); }
		 */
		Pager<WeiAccountQqGroup> pager = weiAccountQqGroupService
				.queryWeiAccountQqGroupListPage(paramMap, pageIndex);
		model.put("pager", pager);
		model.put("jsonParam", jsonParam);
		return "/weiAccountQqGroup/weiAccountQqGroup_list";
	}

	/**
	 * 获取查询条件
	 * 
	 * @param jsonParam
	 * @param model
	 * @return
	 */
	public HashMap<String, Object> getParaMap(String jsonParam, ModelMap model) {
		HashMap<String, Object> newParamMap = newParamMap = new HashMap<String, Object>();
		HashMap<String, Object> paramMap = JsonUtil.toObject(jsonParam,
				HashMap.class);
		Iterator iter = paramMap.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			if (key.toString().equals("name")) {
				newParamMap.put("nameT", val);
			} else if (String.valueOf(val).length() > 0) {
				newParamMap.put(String.valueOf(key), val);
				model.put(String.valueOf(key), val);
			}
		}
		return newParamMap;
	}

	/**
	 * 跳转到分配用户页面.
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/toAssign")
	public String list(
			@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
			Account p, ModelMap model,
			@RequestParam(value = "groupIds", required = true) String groupIds) throws Exception {
		HashMap<String, Object> paramMap = this.getParaMap(jsonParam, model);
		paramMap.put("qtype", "like");
		paramMap.put("type", PlatAccountType.WEI_ACCOUNT.getCode());
		paramMap.put("isDelete", PauseStartType.START.getCode());
		Pager<TgAccount> pager = tgAccountService.queryTgAccountListPage(paramMap,
				pageIndex);
		model.put("pager", pager);
		model.put("jsonParam", jsonParam);
		model.put("groupIds", groupIds);
		model.put("menuClass", "accountManage");
		return "/weiAccountQqGroup/weiAccountQqGroup_assign";
	}

	/**
	 * 批量添加 用户_QQ群
	 * 
	 * @param p
	 *            对象参数
	 * @param 多个群id
	 *            ，以逗号分隔
	 * @return ajax响应
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object addWeiAccountQqGroup(WeiAccountQqGroup p,String groupIds,
			HttpSession session, HttpServletRequest request) {
		try {
			Account account = (Account) session
					.getAttribute(Const.SESSION_USER_KEY);
			// 验证唯一性
			pmap.clear();
			// 一个群只能分配给一个用户
			String[] ids = groupIds == null ? new String[0] : groupIds
					.split(",");
			pmap.put("ids", ids);
			pmap.put("isKick", KickStatus.NOT_KICK.getCode());
			int result = weiAccountQqGroupService
					.getWeiAccountQqGroupListCount(pmap);
			if (result > 0) {
				return GROUP_ASSIGNED;
			}
			p.setIds(ids);
			p.setInPerson(account.getAccountId());
			Date now = new Date();
			p.setInTime(now);
			p.setAddStatusTime(now);
			p.setUpdateTime(p.getInTime());
			p.setQqMemberCount(0);
			p.setAddStatus(JoinStatus.TO_JOIN.getCode());
			p.setImportStatus(ImportStatus.NOT_IMPORT.getCode());
			p.setIsKick(KickStatus.NOT_KICK.getCode());

			weiAccountQqGroupService.addWeiAccountQqGroup(p);
			//更新群分配状态
			for(String tid : ids ){
				TgQqGroup tq = new TgQqGroup();
				tq.setId(Long.parseLong(tid));
				tq.setAssignmentStatus(AssignmentStatus.ASSIGNED.getCode());;
				tgQqGroupService.updateTgQqGroup(tq);
			}

			// 添加成功
			return AjaxResponse.OK;
		} catch (Exception e) {
			e.printStackTrace();
			// 失败
			return AjaxResponse.FAILED;
		}

	}

	/**
	 * 跳转到查看页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toView")
	public String toViewWeiAccountQqGroup(
			@RequestParam(value = "id", required = true) java.lang.Long id,
			ModelMap model) throws Exception {
		if (id == null) {
			return URLConst.ERROR_URL;
		}
		// model.put("p",
		// weiAccountQqGroupService.getWeiAccountQqGroupById(id));
		model.put("pid", id);
		return "/weiAccountQqGroup/weiAccountQqGroup_add";
	}

	/**
	 * 删除 用户_QQ群
	 * 
	 * @param id
	 *            WeiAccountQqGroupID
	 */
	@RequestMapping(value = "/delete")
	public String deleteWeiAccountQqGroup(
			@RequestParam(value = "id", required = true) java.lang.Long id,
			HttpServletRequest request) throws Exception {
		WeiAccountQqGroup p = new WeiAccountQqGroup(id);
		weiAccountQqGroupService.deleteWeiAccountQqGroup(p);
		String s = request.getHeader("Referer");
		String redirectStr = s.substring(s.indexOf("/weiAccountQqGroup/"),
				s.length());
		return "redirect:" + redirectStr;
	}

	/**
	 * ajax删除 用户_QQ群
	 * 
	 * @param id
	 *            WeiAccountQqGroupID
	 */
	@RequestMapping(value = "/ajaxDelete")
	@ResponseBody
	public Object ajaxDeleteWeiAccountQqGroup(
			@RequestParam(value = "id", required = true) java.lang.Long id) {
		try {
			WeiAccountQqGroup p = new WeiAccountQqGroup(id);
			weiAccountQqGroupService.deleteWeiAccountQqGroup(p);
			return AjaxResponse.OK;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResponse.FAILED;
		}
	}

	/**
	 * ajax 根据id查询实体bean
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getById")
	@ResponseBody
	public Object ajaxGetById(
			@RequestParam(value = "id", required = true) java.lang.Long id)
			throws Exception {
		WeiAccountQqGroup p = weiAccountQqGroupService
				.getWeiAccountQqGroupById(id);
		if (p == null) {
			return AjaxResponse.NOEXITS;
		}
		return AjaxResponse.OK(p);
	}

}
